package com.base.controller;


import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.base.comm.CommContent;
import com.base.po.voip.SelfShopCategory;
import com.base.po.voip.SelfShopGoods;
import com.base.po.voip.Users;
import com.base.service.LogsService;
import com.base.service.SelfShopCategoryService;
import com.base.service.SelfShopGoodsService;
import com.base.service.UsersService;
import com.base.utils.IP;
import com.base.utils.Produce;

@Controller
@RequestMapping("/admin")
public class add_SelfShopGoods {
    @Autowired
    private LogsService logsService;// log日志
    @Autowired
    private SelfShopGoodsService selfShopGoodsService;
    @Autowired
    private SelfShopCategoryService selfShopCategoryService;
    @Autowired
    private UsersService usersService;

    // 账户信息
    @RequestMapping("/add_SelfShopGoods")
    public ModelAndView index(HttpServletRequest request) throws Exception {
        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");
        if (adminUserId == null) {
            modelAndView.setViewName("jsp/login");
            return modelAndView;
        }

        Users users = usersService.selectByPrimaryKey(adminUserId);
        List<SelfShopCategory> selfShopCategory = null;
        if (users.getRole() == 0 || users.getRole() == 1) {
            selfShopCategory = selfShopCategoryService.selectByLevel1(adminUserId, adminUserId);
            request.setAttribute("userId", adminUserId);
        }
        if (users.getRole() == 2) {
            selfShopCategory = selfShopCategoryService.selectByLevel1(users.getParentid(), users.getParentid());
            request.setAttribute("userId", users.getParentid());
        }

        request.setAttribute("selfShopCategory", selfShopCategory);

        modelAndView.setViewName("jsp/add_SelfShopGoods");
        return modelAndView;
    }


    String SUCCESS = "success";

    // 添加商品
    @RequestMapping(value = "/insertSelfShopGoodsbyjson", method = RequestMethod.POST)
    public void insertSelfShopGoodsByJson(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject obj)
            throws IOException {
        String goodstext = obj.get("goodstext").toString();
        String showpic = obj.get("showpic").toString();
        String detailpic1 = obj.get("detailpic1").toString();
        String detailpic2 = obj.get("detailpic2").toString();
        Integer stock=Integer.parseInt(obj.get("stock").toString());
        String detailpic3 = obj.get("detailpic3").toString();
        String detailpic4 = obj.get("detailpic4").toString();
        String detailvideo = obj.get("detailvideo").toString();
        String firstclassify = obj.get("firstclassify").toString();
        String secondclassify = obj.get("secondclassify").toString();
        BigDecimal price=new BigDecimal(Double.parseDouble(obj.get("price").toString()));
        BigDecimal memberprice = new BigDecimal(0);
        try {
            memberprice=new BigDecimal(Double.parseDouble(obj.get("memberprice").toString()));
        }catch (Exception e){
            memberprice =null;
        }
        BigDecimal derate=new  BigDecimal(Double.parseDouble(obj.get("derate").toString()));
        String introduce = obj.get("introduce").toString();
        String context = obj.get("context").toString();
        String standard = obj.get("standard").toString();
        String exchange = obj.get("exchange").toString();
        String detailslink = obj.get("detailslink").toString();
        String supplier = obj.get("supplier").toString();
        String color = obj.get("color").toString();
        String size = obj.get("size").toString();
        String account =obj.get("account").toString();
        context=URLDecoder.decode(context,"UTF-8");
        // 返回参数
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String adminId = (String) request.getSession().getAttribute("adminUserId");
        if (adminId == null) {
            out.print("请刷新页面重试！");
            return;
        }

        Users users = usersService.selectByPrimaryKey(adminId);
        List<SelfShopCategory> selfShopCategory = null;
        if (users.getRole() == 0 || users.getRole() == 1) {
            selfShopCategory = selfShopCategoryService.selectByLevel1(adminId, adminId);
        }
        if (users.getRole() == 2) {
            selfShopCategory = selfShopCategoryService.selectByLevel1(users.getParentid(), users.getParentid());
        }
        if (selfShopCategory == null || selfShopCategory.size() < 1) {
            out.print("商城未添加分类，无法添加商品");
            return;
        }
//        if (context != null && context != "undefined" && !context.equals("")) {
//            if (context.length() > DatabaseUtil.getFieldCapacity()) {
//                out.print("商品详情添加的图片过大");
//                return;
//            }
//        }

        if (showpic == "" || showpic == "undefined") {
            showpic = null;
        }
        if (detailpic1 == "" || detailpic1 == "undefined") {
            detailpic1 = null;
        }
        if (detailpic2 == "" || detailpic2 == "undefined") {
            detailpic2 = null;
        }
        if (detailpic3 == "" || detailpic3 == "undefined") {
            detailpic3 = null;
        }
        if (detailpic4 == "" || detailpic4 == "undefined") {
            detailpic4 = null;
        }
        if (detailvideo == "" || detailvideo == "undefined") {
            detailvideo = null;
        }

        if (firstclassify != null && !firstclassify.equals("undefined") && !firstclassify.equals("0")) {
            SelfShopCategory firstCategory = selfShopCategoryService.selectByPrimaryKey(firstclassify);
            if (firstCategory != null) {
                firstclassify = firstCategory.getId();
            } else {
                out.print("未找到对应一级分类");
                return;
            }
        } else {
            firstclassify = null;
        }

        if (secondclassify != null && !secondclassify.equals("undefined") && !secondclassify.equals("0")) {
            SelfShopCategory secondCategory = selfShopCategoryService.selectByPrimaryKey(secondclassify);
            if (secondCategory != null) {
                secondclassify = secondCategory.getId();
            } else {
                out.print("未找到对应二级分类");
                return;
            }
        } else {
            secondclassify = null;
        }

        List<Users> shop = null;
        if (account != null && !account.equals("undefined")) {
            shop = usersService.selectByUserName(account);
            if (shop != null && shop.size() > 0) {
                account = shop.get(0).getId();
            }
        }

        String id = Produce.getUUID();

        if (price.compareTo(derate) ==-1) {
            derate = price;
        }

        int resultCode = 0;

        if (users.getRole() == 0 || users.getRole() == 1) {
            resultCode = selfShopGoodsService.insertSelective(new SelfShopGoods(id, adminId, adminId,
                    goodstext, showpic, detailpic1, detailpic2, detailpic3, detailpic4,
                    detailvideo, firstclassify, secondclassify, null, price, memberprice,
                    derate, account, introduce, context, standard, (byte) 1, exchange, detailslink,
                    (byte) 1, Produce.getNowDate(), Produce.getNowDate(), (byte) 1, stock, supplier, color, size));
        }
        if (users.getRole() == 2) {
            resultCode = selfShopGoodsService.insertSelective(new SelfShopGoods(id, users.getParentid(), adminId,
                    goodstext, showpic, detailpic1, detailpic2, detailpic3, detailpic4,
                    detailvideo, firstclassify, secondclassify, null, price, memberprice,
                    derate, account, introduce, context, standard, (byte) 1, exchange, detailslink,
                    (byte) 1, Produce.getNowDate(), Produce.getNowDate(), (byte) 1, stock, supplier, color, size));
        }

        String usernamesys = (String) request.getSession().getAttribute("useracc");
        if (resultCode == 1) {
            logsService.insert(CommContent.TYPE_UPDATE, "添加" + goodstext + "自营商城商品信息", usernamesys,
                    true, IP.getIpAddr(request));
            out.print(SUCCESS);
        } else {
            logsService.insert(CommContent.TYPE_UPDATE, "添加" + goodstext + "自营商城商品失败", usernamesys,
                    true, IP.getIpAddr(request));
            out.print("更改失败，请您重试");
        }
    }

//    // 添加商品
//    @RequestMapping(value = "/insertSelfShopGoods", method = RequestMethod.POST)
//    public void insertSelfShopGoods(HttpServletRequest request, HttpServletResponse response,
//                                    String goodstext, String showpic, String detailpic1, String detailpic2, Integer stock,
//                                    String detailpic3, String detailpic4, String detailvideo, String firstclassify,
//                                    String secondclassify, BigDecimal price, BigDecimal derate, String introduce,
//                                    String context, String standard, String account, String exchange, String detailslink,
//                                    String supplier, String color, String size) throws IOException {
//
//
//        // 返回参数
//        response.setCharacterEncoding("utf-8");
//        response.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = response.getWriter();
//        String adminId = (String) request.getSession().getAttribute("adminUserId");
//        if (adminId == null) {
//            out.print("请刷新页面重试！");
//            return;
//        }
//
//        Users users = usersService.selectByPrimaryKey(adminId);
//        List<SelfShopCategory> selfShopCategory = null;
//        if (users.getRole() == 0 || users.getRole() == 1) {
//            selfShopCategory = selfShopCategoryService.selectByLevel1(adminId, adminId);
//        }
//        if (users.getRole() == 2) {
//            selfShopCategory = selfShopCategoryService.selectByLevel1(users.getParentid(), users.getParentid());
//        }
//        if (selfShopCategory == null || selfShopCategory.size() < 1) {
//            out.print("商城未添加分类，无法添加商品");
//            return;
//        }
//        if (context != null && context != "undefined" && !context.equals("")) {
//            if (context.length() > DatabaseUtil.getFieldCapacity()) {
//                out.print("商品详情添加的图片过大");
//                return;
//            }
//        }
//
//        if (showpic == "" || showpic == "undefined") {
//            showpic = null;
//        }
//        if (detailpic1 == "" || detailpic1 == "undefined") {
//            detailpic1 = null;
//        }
//        if (detailpic2 == "" || detailpic2 == "undefined") {
//            detailpic2 = null;
//        }
//        if (detailpic3 == "" || detailpic3 == "undefined") {
//            detailpic3 = null;
//        }
//        if (detailpic4 == "" || detailpic4 == "undefined") {
//            detailpic4 = null;
//        }
//        if (detailvideo == "" || detailvideo == "undefined") {
//            detailvideo = null;
//        }
//
//        if (firstclassify != null && !firstclassify.equals("undefined") && !(firstclassify == "0")) {
//            SelfShopCategory firstCategory = selfShopCategoryService.selectByPrimaryKey(firstclassify);
//            if (firstCategory != null) {
//                firstclassify = firstCategory.getId();
//            } else {
//                out.print("未找到对应一级分类");
//                return;
//            }
//        } else {
//            firstclassify = null;
//        }
//
//        if (secondclassify != null && !secondclassify.equals("undefined") && !(secondclassify == "0")) {
//            SelfShopCategory secondCategory = selfShopCategoryService.selectByPrimaryKey(secondclassify);
//            if (secondCategory != null) {
//                secondclassify = secondCategory.getId();
//            } else {
//                out.print("未找到对应二级分类");
//                return;
//            }
//        } else {
//            secondclassify = null;
//        }
//
//        List<Users> shop = null;
//        if (account != null && !account.equals("undefined")) {
//            shop = usersService.selectByUserName(account);
//            if (shop != null && shop.size() > 0) {
//                account = shop.get(0).getId();
//            }
//        }
//
//        String id = Produce.getUUID();
//
//        if (price.compareTo(derate) == -1) {
//            derate = price;
//        }
//
//        int resultCode = 0;
//
//        if (users.getRole() == 0 || users.getRole() == 1) {
//            resultCode = selfShopGoodsService.insertSelective(new SelfShopGoods(id, adminId, adminId,
//                    goodstext, showpic, detailpic1, detailpic2, detailpic3, detailpic4,
//                    detailvideo, firstclassify, secondclassify, null, price, derate, account, introduce,
//                    context, standard, (byte) 1, exchange, detailslink, (byte) 1, Produce.getNowDate(),
//                    Produce.getNowDate(), (byte) 1, stock, supplier, color, size));
//        }
//        if (users.getRole() == 2) {
//            resultCode = selfShopGoodsService.insertSelective(new SelfShopGoods(id, users.getParentid(), adminId,
//                    goodstext, showpic, detailpic1, detailpic2, detailpic3, detailpic4,
//                    detailvideo, firstclassify, secondclassify, null, price, derate, account, introduce,
//                    context, standard, (byte) 1, exchange, detailslink, (byte) 1, Produce.getNowDate(),
//                    Produce.getNowDate(), (byte) 1, stock, supplier, color, size));
//        }
//
//        String usernamesys = (String) request.getSession().getAttribute("useracc");
//        if (resultCode == 1) {
//            logsService.insert(CommContent.TYPE_UPDATE, "添加" + goodstext + "自营商城商品信息", usernamesys,
//                    true, IP.getIpAddr(request));
//            out.print(SUCCESS);
//        } else {
//            logsService.insert(CommContent.TYPE_UPDATE, "添加" + goodstext + "自营商城商品失败", usernamesys,
//                    true, IP.getIpAddr(request));
//            out.print("更改失败，请您重试");
//        }
//    }
    // 添加商品
//	@RequestMapping(value = "/insertSelfShopGoods", method = RequestMethod.POST)
//	public void insertSelfShopGoods(HttpServletRequest request, HttpServletResponse response,
//									SelfShopGoodsRequest goods) throws IOException {
//		// 返回参数
//		response.setCharacterEncoding("utf-8");
//		response.setContentType("text/html;charset=UTF-8");
//		PrintWriter out = response.getWriter();
//		String adminId = (String) request.getSession().getAttribute("adminUserId");
//		if (adminId == null) {
//			out.print("请刷新页面重试！");
//			return;
//		}
//
//		Users users = usersService.selectByPrimaryKey(adminId);
//		List<SelfShopCategory> selfShopCategory = null;
//		if(users.getRole() == 0 || users.getRole() == 1) {
//			selfShopCategory = selfShopCategoryService.selectByLevel1(adminId,adminId);
//		}
//		if(users.getRole() == 2) {
//			selfShopCategory = selfShopCategoryService.selectByLevel1(users.getParentid(), users.getParentid());
//		}
//		if(selfShopCategory == null || selfShopCategory.size() < 1) {
//			out.print("商城未添加分类，无法添加商品");
//			return;
//		}
//
//		if(goods.getShowpic().equals("") || goods.getShowpic() == "undefined") {
//			goods.setShowpic(null);
//		}
//		if(goods.getDetailpic1().equals("") || goods.getDetailpic1() == "undefined") {
//			goods.setDetailpic1(null);
//		}
//		if(goods.getDetailpic2().equals("") || goods.getDetailpic2() == "undefined") {
//			goods.setDetailpic2(null);
//		}
//		if(goods.getDetailpic3().equals("") || goods.getDetailpic3() == "undefined") {
//			goods.setDetailpic3(null);
//		}
//		if(goods.getDetailpic4().equals("") || goods.getDetailpic4() == "undefined") {
//			goods.setDetailpic4(null);
//		}
//		if(goods.getDetailvideo().equals("") || goods.getDetailvideo() == "undefined") {
//			goods.setDetailvideo(null);
//		}
//
//		if(goods.getFirstclassify() != null && !goods.getFirstclassify().equals("undefined") && !goods.getFirstclassify().equals("0")) {
//			SelfShopCategory firstCategory = selfShopCategoryService.selectByPrimaryKey(goods.getFirstclassify());
//			if(firstCategory != null) {
//				goods.setFirstclassify(firstCategory.getId());
//			}else {
//				out.print("未找到对应一级分类");
//				return;
//			}
//		}else {
//			goods.setFirstclassify(null);
//		}
//
//		if(goods.getSecondclassify() != null && !goods.getSecondclassify().equals("undefined") && !goods.getSecondclassify().equals("0")) {
//			SelfShopCategory secondCategory = selfShopCategoryService.selectByPrimaryKey(goods.getSecondclassify());
//			if(secondCategory != null) {
//				goods.setSecondclassify(secondCategory.getId());
//			}else {
//				out.print("未找到对应二级分类");
//				return;
//			}
//		}else {
//			goods.setSecondclassify(null);
//		}
//
//		List<Users> shop = null;
//		if(goods.getAccount() != null && !goods.getAccount().equals("undefined")) {
//			shop = usersService.selectByUserName(goods.getAccount());
//			if(shop != null && shop.size() > 0) {
//				goods.setAccount(shop.get(0).getId());
//			}
//		}
//
//		String id = Produce.getUUID();
//
//		if (goods.getPrice().compareTo(goods.getDerate()) == -1){
//			goods.setDerate(goods.getPrice());
//		}
//
//		int resultCode = 0;
//
//		if(users.getRole() == 0 || users.getRole() == 1) {
//			resultCode = selfShopGoodsService.insertSelective(new SelfShopGoods(id, adminId, adminId,
//					goods.getGoodstext(), goods.getShowpic(), goods.getDetailpic1(), goods.getDetailpic2(), goods.getDetailpic3(), goods.getDetailpic4(),
//					goods.getDetailvideo(), goods.getFirstclassify(), goods.getSecondclassify(), null, goods.getPrice(), goods.getDerate(),
//					goods.getAccount(), goods.getIntroduce(), goods.getContext(), goods.getStandard(), (byte)1, goods.getExchange(), goods.getDetailslink(),
//					(byte)1, Produce.getNowDate(), Produce.getNowDate(), (byte)1, goods.getStock(), goods.getSupplier(), goods.getColor(), goods.getSize()));
//		}
//		if(users.getRole() == 2) {
//			resultCode = selfShopGoodsService.insertSelective(new SelfShopGoods(id, users.getParentid(), adminId,
//					goods.getGoodstext(), goods.getShowpic(), goods.getDetailpic1(), goods.getDetailpic2(), goods.getDetailpic3(), goods.getDetailpic4(),
//					goods.getDetailvideo(), goods.getFirstclassify(), goods.getSecondclassify(), null, goods.getPrice(), goods.getDerate(),
//					goods.getAccount(), goods.getIntroduce(), goods.getContext(), goods.getStandard(), (byte)1, goods.getExchange(), goods.getDetailslink(),
//					(byte)1, Produce.getNowDate(), Produce.getNowDate(), (byte)1, goods.getStock(), goods.getSupplier(), goods.getColor(), goods.getSize()));
//		}
//
//		String usernamesys = (String) request.getSession().getAttribute("useracc");
//		if (resultCode == 1) {
//			logsService.insert(CommContent.TYPE_UPDATE, "添加" + goods.getGoodstext() + "自营商城商品信息", usernamesys,
//					true, IP.getIpAddr(request));
//			out.print(SUCCESS);
//		} else {
//			logsService.insert(CommContent.TYPE_UPDATE, "添加" + goods.getGoodstext() + "自营商城商品失败", usernamesys,
//					true, IP.getIpAddr(request));
//			out.print("更改失败，请您重试");
//		}
//	}
}
